namespace Leey.Net.eTerm
{
    using System;
    using System.Runtime.CompilerServices;

    public class StreamParser
    {
        private int bufsize = 0;
        private byte[] m_buf = new byte[0x1000];
        private object thisLock = new object();

        public event StreamHandler OnStreamElement;

        public event StreamError OnStreamError;

        public void Push(byte[] buf, int offset, int length)
        {
            if (length != 0)
            {
                if (buf[0].ToString("x2") == "01")
                {
                    this.Reset();
                }
                if ((this.bufsize + length) >= 0x1000)
                {
                    throw new Exception("缓冲区过小!");
                }
                Buffer.BlockCopy(buf, offset, this.m_buf, this.bufsize, length);
                this.bufsize += length;
                if (buf[length - 1].ToString("x2") == "03")
                {
                    if (this.OnStreamElement != null)
                    {
                        this.OnStreamElement(this, new CmdResult(this.m_buf, this.bufsize));
                    }
                    this.Reset();
                }
            }
        }

        public void Reset()
        {
            this.bufsize = 0;
        }
    }
}
